package tornadoj.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tornadoj.web.SimpleCache;
import tornadoj.web.TornadoJConfiguration;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tinyms on 13-12-18.
 */
public class Utils {
    private static Logger Log = LoggerFactory.getLogger(Utils.class);
    /**
     * 1024 byte
     */
    public static int KB = 1024;
    /**
     * 1024 M
     */
    public static int MB = 1024 * KB;
    /**
     * 1024 G
     */
    public static int GB = 1024 * MB;
    /**
     * 1024 T
     */
    public static int TB = 1024 * GB;


    //Re valid
    public static int parseInt(String text, int defalutValue) {
        return NumberUtils.toInt(text, defalutValue);
    }

    public static float parseFloat(String text, float defalutValue) {
        return NumberUtils.toFloat(text, defalutValue);
    }

    public static double parseDouble(String text, double defalutValue) {
        return NumberUtils.toDouble(text, defalutValue);
    }

    public static Date parseDate(String text, Date defaultValue) {
        try {
            return DateUtils.parseDate(text, TornadoJConfiguration.DateFormat);
        } catch (ParseException e) {
            Log.warn(e.getLocalizedMessage(), e);
        }
        return defaultValue;
    }

    public static Date parseDate(String text, String formatter, Date defaultValue) {
        try {
            return DateUtils.parseDate(text, formatter);
        } catch (ParseException e) {
            Log.warn(e.getLocalizedMessage(), e);
        }
        return defaultValue;
    }

    public static Date parseDateTime(String text, Date defaultValue) {
        try {
            return DateUtils.parseDate(text, TornadoJConfiguration.DateTimeFormat);
        } catch (ParseException e) {
            Log.warn(e.getLocalizedMessage(), e);
        }
        return defaultValue;
    }

    public static List<String> parseChinese(String text) {
        List<String> chineses = new ArrayList<String>();
        Pattern pattern = Pattern.compile("[\u4E00-\u9FA5]+");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            chineses.add(matcher.group());
        }
        return chineses;
    }

    public static List<String> findNumber(String text) {
        List<String> nums = new ArrayList<String>();
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            nums.add(matcher.group());
        }
        return nums;
    }

    public static String encode(Object o) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        return gson.toJson(o);
    }

    public static String encode(Object o, String dateFormat) {
        Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
        return gson.toJson(o);
    }

    public static <T> T decode(String json, Class<T> c) {
        Gson gson = new Gson();
        return gson.fromJson(json, c);
    }

    //Utils
    public static boolean mkdirs(String path) {
        File dirs = new File(path);
        return dirs.mkdirs();
    }

    public static boolean fileOrDirExists(String path) {
        File entity = new File(path);
        return entity.exists();
    }

    public static String md5(String s) {
        char hexChar[] = {'0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        byte[] b = s.getBytes();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(b);
            byte[] b2 = md.digest();
            char str[] = new char[b2.length << 1];
            int len = 0;
            for (int i = 0; i < b2.length; i++) {
                byte val = b2[i];
                str[len++] = hexChar[(val >>> 4) & 0xf];
                str[len++] = hexChar[val & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    //sql datetime
    public static Timestamp timestamp(Date date) {
        return new Timestamp(date.getTime());
    }

    public static Timestamp current_timestamp() {
        return new Timestamp(Calendar.getInstance().getTime().getTime());
    }

    public static boolean fileModified(File file, String cacheName) {
        final long currentFileTime = file.lastModified();
        String key = Utils.md5(file.getAbsolutePath());
        Long cachedFileTime = (Long) SimpleCache.getCache(key, cacheName);
        //在Cache中不存在，视为修改过
        if (cachedFileTime == null) {
            SimpleCache.setCache(key, currentFileTime, cacheName);
            return true;
        }
        if (currentFileTime > cachedFileTime) {
            SimpleCache.setCache(key, currentFileTime, cacheName);
            return true;
        }
        return false;
    }


//    public static void main(String[] args) {
//
//    }
}
